package com.dingwei.superiordiary.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.adapter.easyViewHolder.FindListAdapter;
import com.dingwei.superiordiary.bean.IndexAttentionBean;
import com.dingwei.superiordiary.mvp.presenter.SearchPostListPresenter;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.utils.ScrollCalculatorHelper;
import com.jude.easyrecyclerview.decoration.DividerDecoration;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.utils.DisplayUtil;
import com.lihao.baselibrary.utils.ScreenUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.SocializeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author 南柯一梦丶
 * Created time 2018/11/2.
 * Personal signature 余生还长 何必慌张
 * Page description :
 * .::::.
 * .::::::::.
 * :::::::::::
 * ..:::::::::::'
 * '::::::::::::'
 * .::::::::::
 * '::::::::::::::..
 * ..::::::::::::.
 * ``::::::::::::::::
 * ::::``:::::::::'        .:::.
 * ::::'   ':::::'       .::::::::.
 * .::::'      ::::     .:::::::'::::.
 * .:::'       :::::  .:::::::::' ':::::.
 * .::'        :::::.:::::::::'      ':::::.
 * .::'         ::::::::::::::'         ``::::.
 * ...:::           ::::::::::::'              ``::.
 * ```` ':.          ':::::::::'                  ::::..
 * '.:::::'                    ':'````..
 */
public class SearchPostListActivity extends BaseActivity implements Contract.SearchPostListView {

    SearchPostListPresenter indexAttentionPresenter = new SearchPostListPresenter(this);
    @Bind(R.id.img_back)
    ImageView imgBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.m_recyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.no_data_layout)
    RelativeLayout noDataLayout;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.no_net_btn)
    TextView noNetBtn;
    @Bind(R.id.no_net_layout)
    RelativeLayout noNetLayout;


    private FindListAdapter adapter;
    private LinearLayoutManager layoutManager;
    private ScrollCalculatorHelper scrollCalculatorHelper;
    boolean mFull = false;
    List<IndexAttentionBean.DataBean.BannerBean> list = new ArrayList<>();

    private String keywords;
    private int page = 1;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_search_post_list;
    }

    @Override
    protected void initData() {
        refreshLayout.autoRefresh();
    }

    @Override
    protected void initView() {
        keywords = getIntent().getStringExtra("keywords");

        tvTitle.setText("搜索结果");
        adapter = new FindListAdapter(BaseActivity.context);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addItemDecoration(new DividerDecoration(getResources().getColor(R.color.bg), DisplayUtil.dip2px(this, 8)));
        mRecyclerView.setNestedScrollingEnabled(false);

        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page = page + 1;
                indexAttentionPresenter.initData(page, keywords, false, false);
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                indexAttentionPresenter.initData(page, keywords, true, false);
            }
        });


        //限定范围为屏幕一半的上下偏移180
//        int playTop = CommonUtil.getScreenHeight(getActivity()) / 2 - CommonUtil.dip2px(SearchPostListActivity.this, 130);
//        int playBottom = CommonUtil.getScreenHeight(getActivity()) / 2 + CommonUtil.dip2px(SearchPostListActivity.this, 130);
        int playTop = ScreenUtils.getScreenHeight(BaseActivity.context) / 4;
        int playBottom = ScreenUtils.getScreenHeight(BaseActivity.context) / 4 * 3;
        //自定播放帮助类
        scrollCalculatorHelper = new ScrollCalculatorHelper(R.id.video_item_player, playTop, playBottom);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            int firstVisibleItem, lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                scrollCalculatorHelper.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();

                //这是滑动自动播放的代码
                if (!mFull) {
                    scrollCalculatorHelper.onScroll(recyclerView, firstVisibleItem, lastVisibleItem, lastVisibleItem - firstVisibleItem + 1);
                }
            }
        });

        adapter.xxInterfaceListener(new FindListAdapter.xxInterFace() {
            @Override
            public void showRightDialog(int position, View view) {
                IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
                indexAttentionPresenter.showSortPopupWindow(view, bean.id, position);
            }

            @Override
            public void showShareDialog(int position, View view) {
                IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
                share_id = bean.id;
                indexAttentionPresenter.showSharePopupWindow(view, bean, position, shareListener);
            }

            @Override
            public void likes(int position) {
                IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
                indexAttentionPresenter.like(bean.id, position);
            }

            @Override
            public void forward(int position) {
                IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
                intent = new Intent(BaseActivity.context, ForwardEditingActiivty.class);
                intent.putExtra("bean", bean);
                startActivity(intent);
            }

            @Override
            public void attentionAction(int position) {
                IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
                if (bean.attentioned == 0) {
                    indexAttentionPresenter.attentionAction(bean.consumer_id, "1", position);
                } else {
                    indexAttentionPresenter.attentionAction(bean.consumer_id, "0", position);
                }
            }

        });
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void OnRefresh(boolean isRefresh, IndexAttentionBean bean) {
        refreshLayout.finishRefresh();
        if (bean.data.list != null && bean.data.list.size() > 0) {
            adapter.clear();
            adapter.addAll(bean.data.list);
            showData("success");
        } else {
            showData("no_data");
        }
    }


    @Override
    public void OnLoadMore(boolean isRefresh, IndexAttentionBean bean) {
        adapter.addAll(bean.data.list);
        refreshLayout.finishLoadmore();
        showData("success");
    }

    @Override
    public void OnFail() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        showData("fail");
    }

    @Override
    public void likeSuccess(int position) {
        if (adapter.getItem(position).is_likes == 0) {
            adapter.getItem(position).likes = (Integer.parseInt(adapter.getItem(position).likes) + 1) + "";
            adapter.getItem(position).is_likes = 1;
        } else {
            adapter.getItem(position).likes = (Integer.parseInt(adapter.getItem(position).likes) - 1) + "";
            adapter.getItem(position).is_likes = 0;
        }
        adapter.notifyDataSetChanged();

    }

    @Override
    public void hateSuccess(int position) {
        adapter.remove(position);
    }

    @Override
    public void attentionActionSuccess(int position) {
        IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
        bean.attentioned = bean.attentioned == 0 ? 1 : 0;
        adapter.notifyDataSetChanged();
    }

    @Override
    public void collectSuccess(int position) {
        showToast("收藏成功");
    }

    private void showData(String state) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        if (state.equals("success")) {
            refreshLayout.setVisibility(View.VISIBLE);
            noDataLayout.setVisibility(View.GONE);
            noNetLayout.setVisibility(View.GONE);
        } else if (state.equals("no_data")) {
            refreshLayout.setVisibility(View.GONE);
            noDataLayout.setVisibility(View.VISIBLE);
            noNetLayout.setVisibility(View.GONE);
        } else {
            refreshLayout.setVisibility(View.GONE);
            noDataLayout.setVisibility(View.GONE);
            noNetLayout.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.img_back, R.id.no_net_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.no_net_btn:
                page = 1;
                indexAttentionPresenter.initData(page, keywords, true, true);
                break;
        }
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (newConfig.orientation != ActivityInfo.SCREEN_ORIENTATION_USER) {
            mFull = false;
        } else {
            mFull = true;
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoPlayer.releaseAllVideos();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 0:
                page = 1;
                indexAttentionPresenter.initData(page, keywords, true, false);
                break;
        }
    }

    String share_id;
    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            SocializeUtils.safeShowDialog(dialog);
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(SearchPostListActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            SocializeUtils.safeCloseDialog(dialog);
            indexAttentionPresenter.shareSuccess(share_id);

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(SearchPostListActivity.this, "分享失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(SearchPostListActivity.this, "取消分享", Toast.LENGTH_LONG).show();

        }
    };
}
